package com.lsk.serviceDriverUser.service;

import com.lsk.internalcommon.DTO.DriverUser;
import com.lsk.internalcommon.DTO.DriverUserWorkStatus;
import com.lsk.internalcommon.DTO.ResponseResult;
import com.lsk.internalcommon.constant.CommonStatusEnum;
import com.lsk.internalcommon.constant.DriverCarConstants;
import com.lsk.serviceDriverUser.mapper.DriverUserMapper;
import com.lsk.serviceDriverUser.mapper.DriverUserWorkStatusMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DriverUserService {

    @Autowired
    private DriverUserMapper driverUserMapper;
    @Autowired
    private DriverUserWorkStatusMapper driverUserWorkStatusMapper;

    public ResponseResult getDriverUser(){
        DriverUser driverUser = driverUserMapper.selectById(1);
        return ResponseResult.success(driverUser);
    }

    public ResponseResult addDriverUser(DriverUser user){
        LocalDateTime now = LocalDateTime.now();
        user.setGmtCreate(now);
        user.setGmtModified(now);
        //添加到司机状态表中
        DriverUserWorkStatus driverUserWorkStatus = new DriverUserWorkStatus();
        driverUserWorkStatus.setDriverId(user.getId());
        driverUserWorkStatus.setWorkStatus(DriverCarConstants.DRIVER_USER_STATUS_STOP);
        driverUserWorkStatus.setGmtCreate(now);
        driverUserWorkStatus.setGmtModified(now);
        driverUserWorkStatusMapper.insert(driverUserWorkStatus);

        int insert = driverUserMapper.insert(user);
        if (insert == 1){
            return ResponseResult.success("新增成功");
        }
            return ResponseResult.fail("新增失败");
    }

    public ResponseResult updateDriverUser(DriverUser user){
        LocalDateTime now = LocalDateTime.now();
        user.setGmtModified(now);
        int i = driverUserMapper.updateById(user);
        if (i == 1){
            return ResponseResult.success("修改成功");
        }
        return ResponseResult.fail("修改失败");
    }

    /**
     * 根据手机号判断司机是否存在
     * @param driverPhone
     * @return
     */
    public ResponseResult<DriverUser> getDriverUserByPhone(String driverPhone){
        Map<String,Object> map = new HashMap<>();
        map.put("driver_phone",driverPhone);
        map.put("state", DriverCarConstants.DRIVER_STATUS_VALID);
        List<DriverUser> driverUsers = driverUserMapper.selectByMap(map);
        if (driverUsers.isEmpty()){
            return ResponseResult.fail(CommonStatusEnum.DRIVER_USER_NOT_EXISTS.getCode(),CommonStatusEnum.DRIVER_USER_NOT_EXISTS.getValue());
        }
        return ResponseResult.success(driverUsers.get(0));
    }
}
